
import React, { Component } from 'react'
import { Button, FlatList, Modal, View } from 'react-native'
import UserAddor from './s182/UserAddor'
import UserEditor from './s182/UserEditor'
import {users} from './s182/users.json'
import UserShow from './s182/UserShow'
let max=2
export default class App extends Component {
  state={users,addorVisible:false,editorVisible:false,currentId:1}
  _openAddor=()=>this.setState({addorVisible:true})
  _delete=id=>{
    let users=this.state.users
    let index=users.findIndex(user=>user.id===id)
    users.splice(index,1)
    this.setState({users})
  }

  _showUserEditor=id=>{
    this.setState({currentId:id,editorVisible:true})
  }

  _add=user=>{
    console.log(user)
    let users=this.state.users
    user.id=++max
    users.push(user)
    this.setState({users,addorVisible:false})
  }
  _update=user=>{
    let users=this.state.users
    let index=users.findIndex(u=>u.id===user.id)
    users.splice(index,1,user)
    this.setState({users,editorVisible:false})
  }
  
  _renderUser=({item:user})=><UserShow user={user} 
  onDelete={this._delete} onUpdate={this._showUserEditor}/>
  render() {
    return (
      <View>
      {/* 添加 */}
        <Modal visible={this.state.addorVisible} transparent={true} animationType="fade">
          <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
            <View style={{width:300,height:300,backgroundColor:'antiquewhite'}}>
                <UserAddor onUserAdd={this._add}/>
            </View>
          </View>
        </Modal>
      {/* 更新 */}
        <Modal visible={this.state.editorVisible} transparent={true} animationType="fade">
          <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
            <View style={{width:300,height:300,backgroundColor:'antiquewhite'}}>
                <UserEditor id={this.state.currentId} onUserUpdate={this._update}/>
            </View>
          </View>
        </Modal>


        <Button title="添加" onPress={this._openAddor}/>
        <FlatList data={this.state.users} 
        renderItem={this._renderUser} keyExtractor={user=>user.id}/>
      </View>
    )
  }
}
